<template>
  <CommonPage>
    <AppCrud
      ref="tableRef"
      :columns="columns"
      default-sort="date"
      v-model:query="query"
      :get-data="recordApi.page"
    >
      <query-item label="员工姓名">
        <a-input
          allow-clear
          size="small"
          placeholder="请输入员工姓名"
          v-model:value="query.worker"
        ></a-input>
      </query-item>
      <query-item label="日期">
        <a-date-picker
          allow-clear
          size="small"
          class="w-160"
          placeholder="请选择日期"
          v-model:value="query.date"
        ></a-date-picker>
      </query-item>

      <template #action>
        <a-button type="primary" @click="handleAdd">
          <template #icon><PlusOutlined></PlusOutlined></template>
          生产录入
        </a-button>
      </template>
    </AppCrud>

    <AppModal ref="modalRef" width="500px">
      <a-form ref="formRef" :model="formModel" :label-col="{ style: { width: '90px' } }">
        <a-form-item label="日期" name="date">
          <a-date-picker
            :disabled="modalAction == 'edit'"
            class="w-full"
            v-model:value="formModel.date"
          ></a-date-picker>
        </a-form-item>
        <a-form-item
          label="员工"
          name="workerId"
          :rules="[{ required: true, message: '此为必选项' }]"
        >
          <a-select
            :filter-option="filterOption"
            show-search
            :disabled="modalAction == 'edit'"
            v-model:value="formModel.workerId"
            placeholder="请选择员工"
          >
            <a-select-option
              v-for="worker in workers"
              :key="worker.code"
              :label="worker.name"
              :value="worker.id"
            >
              {{ worker.code }} | {{ worker.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="款式"
          name="styleId"
          :rules="[{ required: true, message: '此为必选项' }]"
        >
          <a-select
            show-search
            :disabled="modalAction == 'edit'"
            :filter-option="filterStyleOption"
            v-model:value="formModel.styleId"
            placeholder="请选择款式"
            :default-active-first-option="false"
            :not-found-content="null"
            :options="styles"
          ></a-select>
        </a-form-item>
        <a-form-item
          label="尺寸"
          name="sizeId"
          v-if="formModel.styleId"
          :rules="[{ required: true, message: '此为必选项' }]"
        >
          <a-select
            :disabled="modalAction == 'edit'"
            v-model:value="formModel.sizeId"
            placeholder="请选择款式"
          >
            <a-select-option v-for="size in sizes" :value="size.sizeId">
              {{ size.size.name }} ({{ size.amount }}件)
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="工序"
          name="processId"
          v-if="formModel.styleId"
          :rules="[{ required: true, message: '此为必选项' }]"
        >
          <a-select
            show-search
            :disabled="modalAction == 'edit'"
            :filter-option="filterProcessOption"
            v-model:value="formModel.processId"
            placeholder="请选择工序"
          >
            <a-select-option v-for="p in process" :label="p.index + ' ' + p.name" :value="p.id">
              {{ p.index }} {{ p.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="数量"
          :rules="[
            {
              required: true,
              message: '此为必填项',
            },
            {
              min: 1,
              type: 'number',
              message: '必须大于1',
            },
          ]"
          name="number"
        >
          <a-input-number :min="0" :step="1" v-model:value="formModel.number"></a-input-number>
        </a-form-item>
        <a-form-item label="备注">
          <a-textarea
            placeholder="请输入备注信息"
            v-model:value="formModel.description"
          ></a-textarea>
        </a-form-item>
      </a-form>
      <template v-if="modalAction == 'add'" #buttons="{ loading }">
        <a-button @click="onNext" :loading="loading">提交且下一个</a-button>
      </template>
    </AppModal>
  </CommonPage>
</template>
<script setup lang="ts">
import { AppCrud, AppModal, CommonPage, QueryItem } from '@/components/common'
import { useCrud } from '@/hooks/useCrud.ts'
import recordApi, { CreateRecordDto } from '@/api/record.ts'
import styleApi from '@/api/style.ts'
import { Button, message, Modal, Space } from 'ant-design-vue'
import workerApi, { WorkerDto } from '@/api/worker.ts'
import { SizeDto } from '@/api/size.ts'
import { ProcessDto } from '@/api/process.ts'
import dayjs from 'dayjs'

const tableRef = ref()

const query = ref({
  worker: null,
  date: null,
})

const workers = ref<WorkerDto[]>([])
const styles = ref<{ value: string; label: string; sizes: SizeDto[] }[]>([])
const process = ref<ProcessDto[]>([])

const columns = [
  {
    title: '日期',
    dataIndex: 'date',
    width: 100,
    render: ({ record }) => {
      return h('div', dayjs(record.date).format('YYYY-MM-DD'))
    },
  },
  {
    title: '用户',
    dataIndex: 'worker',
    width: 120,
    align: 'center',
    render: ({ record }) => {
      return h('div', record.worker.name)
    },
  },
  {
    title: '款式',
    dataIndex: 'style',
    width: 200,
    render: ({ record }) => {
      return h(
        'div',
        `${record.style.group?.name} ${record.style.model?.code} (${record.style.model?.name}) ${record.size.name}`,
      )
    },
  },
  {
    title: '工序',
    dataIndex: 'process',
    width: 180,
    render: ({ record }) => {
      return h('div', `${record.process.index}-${record.process.name}`)
    },
  },
  {
    title: '数量',
    dataIndex: 'number',
    width: 100,
    align: 'center',
  },
  {
    title: '创建时间',
    width: 150,
    dataIndex: 'createdAt',
  }, {
    title: '更新时间',
    width: 150,
    dataIndex: 'updatedAt',
  },
  {
    title: '操作',
    align: 'center',
    width: 140,
    render: ({ record }: any) => {
      return h(
        Space,
        {},
        {
          default: () => [
            h(
              Button,
              {
                size: 'small',
                type: 'primary',
                onClick: () => {
                  handleEdit(record)
                },
              },
              {
                default: () => '编辑',
              },
            ),
            h(
              Button,
              {
                size: 'small',
                danger: true,
                onClick: () => handleDelete(record.id),
              },
              {
                default: () => '删除',
              },
            ),
          ],
        },
      )
    },
  },
]

const {
  modalRef,
  formRef,
  formModel,
  modalAction,
  handleEdit,
  handleAdd,
  handleSave,
  handleDelete,
  validation,
  okLoading,
} = useCrud<CreateRecordDto>({
  name: '记录',
  initForm: {
    workerId: null,
    processId: null,
    number: 0,
    date: dayjs(),
    description: null,
    styleId: null,
    sizeId: null,
  },
  doCreate: recordApi.create,
  doUpdate: recordApi.update,
  doDelete: recordApi.delete,
  doGet: (id) => {
    return new Promise((resolve) => {
      recordApi.get(id).then(({ data }) => {
        data.date = dayjs(data.date)
        resolve({ data })
      })
    })
  },
  refresh: () => tableRef.value?.handleSearch(),
})

const sizes = computed(() => {
  if (formModel.value.styleId) {
    const sizes = styles.value.find((s) => s.value == formModel.value.styleId).sizes
    if (sizes.length > 0) {
      formModel.value.sizeId = sizes[0].sizeId
    } else {
      formModel.value.sizeId = []
    }
    return sizes
  } else {
    return []
  }
})

watch(
  () => formModel.value.styleId,
  (v: string | null) => {
    if (v) {
      styleApi.get(v).then(({ data }) => {
        process.value = data.process
      })
    }
  },
)

function onNext() {
  validation().then((form) => {
    Modal.confirm({
      title: '提示',
      type: 'info',
      content: '确定提交当前记录吗?',
      onOk() {
        okLoading.value = true

        recordApi
          .create(form)
          .then(() => {
            okLoading.value = false
            message.success('提交成功！')
            formModel.value.number = 0
            tableRef.value?.handleSearch()
          })
          .catch((e) => {
            message.error(e.message)
            okLoading.value = false
          })
      },
      onCancel() {},
    })
  })
}

function filterOption(input, option) {
  return option.key.indexOf(input) > -1 || option.label.indexOf(input) > -1
}

function filterStyleOption(input, option) {
  return option.label.indexOf(input) > -1
}

function filterProcessOption(input, option) {
  return option.label.indexOf(input) > -1
}

onMounted(() => {
  tableRef.value?.handleSearch()

  workerApi.all().then(({ data }) => {
    workers.value = data
  })

  styleApi
    .page({
      page: 1,
      sort: 'createdAt',
      order: 'desc',
      size: 200,
      model: {},
    })
    .then(({ data }) => {
      styles.value = data.record.map((item) => {
        console.log(item.id)
        return {
          label: `${item.group.name} ${item.model.code} (${item.model.name})`,
          value: item.id,
          sizes: item.sizes,
        }
      })
    })
})
</script>

<style scoped></style>
